//
//  TestVC.swift
//  QSActivityIndicatorView
//
//  Created by 火星人 on 2017/11/7.
//  Copyright © 2017年 火星人. All rights reserved.
//

import UIKit

class TestVC: UIViewController {

    var tableView = UITableView()
    
    let refreshControl = QSRefreshControl()
    let refreshControlBottom = QSRefreshControl()
    
    
    override func viewDidLoad() {
        
        self.view.addSubview(tableView)
        self.tableView.frame = self.view.frame
        
        refreshControl.bindTo(tableView) { (scrollView, indicator) in
            doInMainThreadAfter(3, task: {
                [weak self] in
                self?.refreshControl.stop()
            })
        }
        
        refreshControlBottom.position = .bottom
        refreshControlBottom.bindTo(tableView) { (scrollView, indicator) in
            doInMainThreadAfter(3, task: {
                [weak self] in
                self?.refreshControlBottom.stop()
            })
        }
        
        refreshControl.start()
    }
}

// MARK: 延迟一段时间后再主线程中执行
public func doInMainThreadAfter(_ delay:Double, task:@escaping ()->()) {
    DispatchQueue.main.asyncAfter(
        deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(delay * 1000)), execute: task)
}

public func doInBackgroundAfter(_ delay:Double, task:@escaping ()->()) {
    DispatchQueue.global(qos: .background).asyncAfter(
        deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(delay * 1000)), execute: task)
}

func doInMainThread(_ task: @escaping (() -> Void)){
    DispatchQueue.main.async(execute: task)
}

func doInBackground(_ task:@escaping (() -> Void), completion:(() -> Void)?){
    
    DispatchQueue.global(qos: .background).async { () -> Void in
        task()
        guard completion != nil else {
            return
        }
        completion!()
    }
}
